package com.shxy.controller;

import com.shxy.common.entity.CustomResult;
import com.shxy.common.enums.ResultCode;
import com.shxy.controller.ui.NewsItem;
import com.shxy.controller.ui.NewsTableItem;
import com.shxy.controller.ui.Option;
import com.shxy.controller.ui.Pageable;
import com.shxy.entity.news.NewsCatagory;
import com.shxy.entity.news.NewsContent;
import com.shxy.entity.news.NewsInfo;
import com.shxy.entity.security.CustomUser;
import com.shxy.service.IFileService;
import com.shxy.service.INewsService;
import com.shxy.service.ISecurityService;
import com.shxy.service.bean.NewsBean;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 新闻管理控制器
 */
@RestController
@RequestMapping("/v1/news")
@Log
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private ISecurityService securityService;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/image/upload")
    public CustomResult uploadImage(MultipartFile file, @RequestHeader(value = "X-token", defaultValue = "") String token) throws IOException {
        if(!token.isBlank()){
            String url = fileService.fileUpload(file, token);
            return new CustomResult(url);
        }
        return new CustomResult(ResultCode.NO_PERMISSION);
    }

    /**
     * 根据编号查询新闻
     * @param id
     * @return
     */
    @GetMapping("/get/id/{id}")
    public CustomResult getNewsById(@PathVariable(name = "id") String id) {
        Optional<NewsInfo> ni = newsService.getById(id);
        if(ni.isEmpty()) {
            return CustomResult.create(ResultCode.PARAM_NOT_VALID);
        }
        NewsInfo newsInfo = ni.get();
        NewsItem newsItem = new NewsItem();
        BeanUtils.copyProperties(newsInfo, newsItem);
        newsItem.setUser(newsInfo.getAuthorId());
        newsItem.setContent(newsInfo.getContent().getContent());

        return CustomResult.create(newsItem);
    }

    /**
     * 查询新闻列表
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public CustomResult getNewsList(@RequestParam(name = "page", defaultValue = "1") int page,
                                    @RequestParam(name = "size", defaultValue = "10") int size) {
        // 1、获取新闻信息列表
        Pageable<NewsBean> nbs = newsService.getList(page, size);
        List<NewsTableItem> ntis = nbs.getItems().stream().map(newsBean -> {
            NewsTableItem nti = new NewsTableItem();
            BeanUtils.copyProperties(newsBean, nti);
            return nti;
        }).collect(Collectors.toList());
        return CustomResult.create(new Pageable<>(nbs.getTotal(), ntis, page, size));
    }

    /**
     * 保存新闻
     * @param news
     * @param user
     * @return
     */
    @PostMapping("/save")
    public CustomResult saveNews(@RequestBody NewsItem news, @RequestHeader(value = "X-token", defaultValue = "") String user) {
        // 1、检查输入
        if(news.getTitle().isBlank() || news.getContent().isBlank()){
            return CustomResult.create(ResultCode.PARAM_IS_BLANK);
        }

        // 2、读取或创建新闻对象
        Optional<NewsInfo> newsInfo = !news.getId().isBlank() ? newsService.getById(news.getId()) : Optional.of(new NewsInfo());

        if(newsInfo.isEmpty()) {
            return CustomResult.create(ResultCode.PARAM_NOT_VALID);
        }

        // 查询密码信息
        Optional<CustomUser> pwd = securityService.getUserByCode(user);
        if(pwd.isEmpty()){
            return CustomResult.create(ResultCode.PARAM_NOT_VALID);
        }

        NewsInfo ni = newsInfo.get();
        // 3、拷贝新闻属性
        BeanUtils.copyProperties(news, ni);
        ni.setAuthorId(pwd.get().getCode());
        ni.setUpdateTime((new Date()).getTime());

        Optional<NewsInfo> op = newsService.save(ni, news.getContent());

        // 4、保存新闻
        if(!op.isEmpty()) {
            BeanUtils.copyProperties(op.get(), news);
            news.setUser(user);
            return CustomResult.create(news);
        }

        return CustomResult.create(ResultCode.COMMON_FAIL);
    }

    /**
     * 获取栏目列表
     * @return
     */
    @GetMapping("/catagory/list")
    public CustomResult getCatagoryList() {
        List<NewsCatagory> catagories = newsService.getCatagoryList();
        List<Option> ops = catagories.stream().map(newsCatagory -> Option.create(newsCatagory.getId(), newsCatagory.getName())).collect(Collectors.toList());
        return CustomResult.create(ops);
    }
}
